package com.yt.wx.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.order.api.interfaces.OrderInfoService;
import com.yt.order.api.interfaces.WxReserveService;
import com.yt.order.api.model.WxReserve;
import com.yt.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/wx")
public class WechatReserveAction {

    @Autowired
    private WxReserveService wxReserveService;
    @Autowired
    private OrderInfoService orderInfoService;
    @RequestMapping("/toReserve")
    @ResponseBody
    public ModelAndView toReserve(HttpServletRequest request){
        String mv = request.getParameter("mv");
        ModelAndView mav = new ModelAndView(mv == null ? "reserve":mv);
        System.out.println("toReserve:" + getOpenId(request));
        return mav;
    }
    @RequestMapping("/success")
    @ResponseBody
    public ModelAndView  success(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("reserve-success");

        return mav;
    }

    @RequestMapping("/cancel")
    @ResponseBody
    public Object  cancel(@RequestParam(value="id", required = true) Long id,
                                HttpServletRequest request){
        MsgBean msg = new MsgBean();
        ModelAndView mav = new ModelAndView("reserve-success");
        System.out.println("cancel:" + getOpenId(request));
        WxReserve reserve = wxReserveService.get(id);
        reserve.setStatus("-1");
        wxReserveService.update(reserve);
        return msg;
    }

    @RequestMapping("/myReserve")
    @ResponseBody
    public ModelAndView myReserve(@RequestParam(value="code", required = false) String code,
                                  HttpServletRequest request){
        Object wechatOpenId = getOpenId(request);
        System.out.println("myReserve:" + wechatOpenId);
        if(code != null && wechatOpenId == null){
            wechatOpenId = resolveOpenId(code);
            setOpenId(request, wechatOpenId.toString());
        }
        System.out.println("myReserve2:" + getOpenId(request));
        ModelAndView mav = new ModelAndView("myreserve");
        if(wechatOpenId != null) {
            QueryFilter filter = new DynamicSQLFilterImpl();
            filter.addFilter("Q_openid_S_EQ", wechatOpenId.toString());
            filter.setSortField("id", true);
            List<WxReserve> list = wxReserveService.find(filter);
            mav.addObject("list", list);
        }
        return mav;
    }

    private String resolveOpenId(String code){
        String response = HttpClientUtil.sendHttpGetRequest("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxc56550b08f3de65c&secret=ef4b88e6b76e09b27847e38b918526ca&code="+code+"&grant_type=authorization_code");
        JSONObject jsonObject = JSON.parseObject(response);
        System.out.println(response);
        return jsonObject.getString("openid");
    }
    @RequestMapping("/reserve")
    @ResponseBody
    public Object reserve(@RequestParam(value="customer", required = true) String customer,
                          @RequestParam(value="city", required = true) String city,
                          @RequestParam(value="institution", required = true) String institution,
                          @RequestParam(value="branch", required = false) String branch,
                          @RequestParam(value="mobile", required = true) String mobile,
                          @RequestParam(value="card", required = false) String card,
                          @RequestParam(value="reserveDate", required = true) String reserveDate,
                          @RequestParam(value="name", required = true) String name,
                          @RequestParam(value="sex", required = false) String sex,
                          @RequestParam(value="identity", required = true) String identity,
                          @RequestParam(value="comments", required = false) String comments,
                          @RequestParam(value="address", required = false) String address,
                          HttpServletRequest request
                          ) {

        String openId = getOpenId(request);
        System.out.println("reserve" + openId);
        MsgBean msg = new MsgBean();
//        QueryFilter orderFilter = new DynamicSQLFilterImpl();
//        orderFilter.addFilter("Q_mobile_S_EQ", mobile);
//        orderFilter.addFilter("Q_idCard_S_EQ", identity);
//        orderFilter.setPagingBean(new PagingBean(0,1));
//        orderFilter.setSortField("id", true);
//        List<OrderInfo> orderInfoList = orderInfoService.find(orderFilter);
//        if(orderInfoList == null || orderInfoList.isEmpty()){
//            return msg.failure("不存在该身份证号对应的用户信息！");
//        }
//        OrderInfo orderInfo = orderInfoList.get(0);
//        if(orderInfo.getBespeaked() !=null && "1".equals(orderInfo.getBespeaked())){
//            return msg.failure("该身份证号用户已经预约");
//        }
        WxReserve reserve = null;

        reserve = new WxReserve();
        reserve.setCustomer(customer);
        reserve.setName(name);
        reserve.setMobile(mobile);
        reserve.setCity(city);
        reserve.setInstitution(institution);
        reserve.setBranch(branch);
        reserve.setAddress(address);
        reserve.setIdentity(identity);
        reserve.setComments(comments);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try{
            date = fmt.parse(reserveDate);
        }catch(Exception ex){}
        reserve.setReserveDate(date.getTime()/1000);
        if(openId != null){
            reserve.setOpenid(openId.toString());
        }
        wxReserveService.insert(reserve);

        return msg;
    }

    private String getOpenId(HttpServletRequest request){
        Object obj = request.getSession().getAttribute("WechatOpenId");
        return obj != null ?obj.toString() : null;
    }

    private void setOpenId(HttpServletRequest request, String openId){
        request.getSession().setAttribute("WechatOpenId", openId);
    }
}
